/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package luft27.comm.mavlink;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

/**
 *
 * @author amalikov
 */
public class ParamSet implements MessagePayload {
	public float param_value;
	public byte target_system;
	public byte target_component;
	public String param_id;
	public byte param_type;

	@Override
	public byte[] get() {
		ByteBuffer bb = ByteBuffer.allocate(256).order(ByteOrder.LITTLE_ENDIAN);
		bb.putFloat(param_value);
		bb.put(target_system);
		bb.put(target_component);
		bb.put(getParamId());
		bb.put(param_type);
		return Arrays.copyOf(bb.array(), bb.position());
	}

	@Override
	public void set(byte[] data) {
		ByteBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
		param_value = bb.getFloat();
		target_system = bb.get();
		target_component = bb.get();
		byte[] idbuf = new byte[16];
		bb.get(idbuf);
		setParamId(idbuf);
		param_type = bb.get();
	}
	
	private byte[] getParamId() {
		byte[] res = param_id.getBytes();
		int n = Math.min(res.length, 16);
		res = Arrays.copyOf(res, 16);
		if (n < 16)
			Arrays.fill(res, n, 15, (byte)0);
		return res;
	}
	
	private void setParamId(byte[] buf) {
		int n = 0;
		while (n < buf.length && buf[n] != 0)
			++n;
		
		param_id = new String(Arrays.copyOf(buf, n));
	}
}
